import dayjs from "dayjs";
import * as R from 'ramda';
const baseURL = import.meta.env.VITE_APP_BASE_API
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

export function parseTime(time, pattern = 'YYYY-MM-DD HH:mm:ss') {
  return dayjs(time).format(pattern)
}

// 通用下载方法
export function download(fileName, delFlag) {
  if (delFlag === undefined) {
    delFlag = true
  }
  window.location.href = baseURL + '/common/download?fileName=' + encodeURI(fileName) + '&delete=' + delFlag
}
// 通用下载方法
export function downloadByPath(filePath, delFlag) {
  if (delFlag === undefined) {
    delFlag = true
  }
  window.location.href = baseURL + '/common/downloadByPath?filePath=' + encodeURI(filePath) + '&delete=' + delFlag
}

/**
 * 按展开几层展开树
 * @param {Object} nodes
 * @param {Object} expandLevel
 * @param {Object} expandedRowKeys 记录展开key
 */
export function expandTree(nodes, expandLevel, keys) {
  let expandedRowKeys = keys || []
  if (expandLevel > 1) {
    // 最后一层不展开
    nodes.forEach(node => {
      expandedRowKeys.push(node.id)
      expandLevel = expandLevel - 1
      if (node.children) {
        return expandTree(node.children, expandLevel, expandedRowKeys)
      }
    })
  }
  return expandedRowKeys
}
export function findTreeById(tree, id) {
  let result;
  tree.find((d) => {
    if (d.id === id) {
      result = d
      return true
    } else if (d.children && !result) {
      result = findTreeById(d.children, id)
      return Boolean(result)
    }
  })
  return result
}

// 转换字符串，undefined,null等转化为''
export function praseStrEmpty(str) {
  if (!str || str === 'undefined' || str === 'null') {
    return ''
  }
  return str
}

// 回显数据字典
export function selectDictLabel(datas, value) {
  var actions = []
  Object.keys(datas).some((key) => {
    if (datas[key].dictValue === ('' + value)) {
      actions.push(datas[key].dictLabel)
      return true
    }
  })
  return actions.join('')
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
  var actions = []
  var currentSeparator = undefined === separator ? ',' : separator
  var temp = value.split(currentSeparator)
  Object.keys(value.split(currentSeparator)).some((val) => {
    Object.keys(datas).some((key) => {
      if (datas[key].dictValue === ('' + temp[val])) {
        actions.push(datas[key].dictLabel + currentSeparator)
      }
    })
  })
  return actions.join('').substring(0, actions.join('').length - 1)
}

export function rangeQueryNormalize(param, isWrap = true) {
  let result = { ...param }
  Object.keys(result).forEach(key => {
    if (key.includes('-')) {
      if (isWrap && result[key] && result[key].length) {
        if (!result.params) result.params = {}
        result.params[key.split('-')[0]] = result[key] && result[key][0]
        result.params[key.split('-')[1]] = result[key] && result[key][1]
      } else if (result[key] && result[key].length) {
        result[key.split('-')[0]] = result[key][0]
        result[key.split('-')[1]] = result[key][1]
      }

      delete result[key]
    }
  })
  return result
}

export function removeEmptyDeep(obj) {
  if (R.is(Object, obj) && !R.is(Array, obj) && !R.is(File, obj) && !R.is(Blob, obj)) {
    return R.reduce(
      (acc, key) => {
        const value = obj[key];
        if (!R.isNil(value) && !(R.is(Object, value) && R.isEmpty(value)) && !(R.is(Array, value) && R.isEmpty(value))) {
          acc[key] = R.is(Object, value) || R.is(Array, value)
            ? removeEmptyDeep(value)
            : value;
        }
        return acc;
      },
      {},
      R.keys(obj)
    );
  } else if (R.is(Array, obj) && !R.is(File, obj) && !R.is(Blob, obj)) {
    return R.map(removeEmptyDeep, obj).filter(x => !R.isNil(x) && !(R.is(Object, x) && R.isEmpty(x)) && !(R.is(Array, x) && R.isEmpty(x)));
  } else {
    return obj;
  }
};

/**
 * @param {String || Number} msg value: 403
 * window.location.origin 通知地址的origin
 */
export function sendMessageToParent(data) {
  console.log('应用集成向外传递', data)
  if (!data && !window.top) return
  window.top.postMessage(data, '*')
}

// 按照环境返回location
export function getLocation() {
  if (window.__MICRO_APP_ENVIRONMENT__) {
    return window.microApp.location
  }
  return window.location
}

// 深拷贝
export function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj))
}

